package com.cqie.secondhandtransaction.utils;

import com.cqie.secondhandtransaction.DTO.UserDetailsDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

public class WebSecurityUtil {

    //Token key
    private static String tokenKey = "Authorization";
    //Token 前缀
    private static String tokenHead = "Bearer ";

    protected static void setTokenKeyAndHead(String configTokenKey, String configTokenHead) {
        if (StringUtils.isNotBlank(configTokenKey)) {
            tokenKey = configTokenKey;
        }
        if (StringUtils.isNotBlank(configTokenHead)) {
            tokenHead = configTokenHead;
        }
    }

    /**
     * 获取当前登录者对象
     */
    public static UserDetailsDTO getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal != null && principal instanceof UserDetailsDTO) {
                return (UserDetailsDTO) principal;
            }
        }
        return null;
    }

    /**
     * 获取当前token
     */
    public static String getCurrentToken() {
        HttpServletRequest request = SpringWebUtil.getRequest();
        if (Objects.isNull(request)) {
            return null;
        }
        String token = request.getHeader(tokenKey);
        if (StringUtils.isBlank(token)) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if (tokenKey.equals(cookie.getName())) {
                        token = cookie.getValue();
                        break;
                    }
                }
            }
        }
        if (token != null && token.length() > tokenHead.length()) {
            token = token.substring(tokenHead.length());
        }
        return token;
    }

}
